# coding=utf-8
# author:xc
# datetime:2018/8/1 17:43

from . import api

from dbConnection.MysqlConn import Mysql
from app import util
from flask import request, render_template
from math import radians, cos, sin, asin, sqrt
import requests, json, random
import time, hashlib
from app import redis

appid = 'wx087bed01c194a785'
secret = 'e19da6efb5b79d404ef807ea8e113b2c'


@api.route('/api/get/ticket', methods=['POST', 'GET'])
def api_get_ticket():
    try:
        html_url = request.values.get('url')
        timestamp = str(int(time.time()))
        nonceStr = ''.join(random.sample(
                ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g',
                 'f', 'e', 'd', 'c', 'b', 'a'], 8))
        if redis.get('access_token') is None:
            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (
                appid, secret)
            res = requests.get(url)
            s = json.loads(res.text)
            redis.set("access_token", str(s['access_token']), ex=7000)
        if redis.get('jsapi_ticket') is None:
            access_token = redis.get('access_token')
            urls = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi" % (access_token)
            res = requests.get(urls)
            s1 = json.loads(res.text)
            redis.set('jsapi_ticket', s1['ticket'], ex=7000)
        jsapi_ticket = redis.get('jsapi_ticket')
        sign_str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + html_url
        key = hashlib.sha1(sign_str).hexdigest()
        data = {
            'appId': appid,
            'timestamp': timestamp,
            'nonceStr': nonceStr,
            'signature': key,
            'code': util.CODE_SUCCESS
        }
        return util.to_json(data)
    except Exception as e:
        print e
        data = {
            'code': util.CODE_ERROR
        }
        return util.to_json(data)


@api.route('/api/store/list', methods=['POST', 'GET'])
def api_store_list():
    try:
        longitude = request.values.get('lng', default=0)
        latitude = request.values.get('lat', default=0)
        mysql = Mysql()
        sql = "select a.* ,b.machineId,b.machineNum from store as a  left join car_machine as b on a.storeId=b.storeId where a.status=1 "
        result = mysql.getAll(sql, None)
        mysql.dispose()
        data = []
        code = util.CODE_EMPTY
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                storeData = dict()
                storeData['storeId'] = x['storeId']
                storeData['storeName'] = x['storeName']
                storeData['province'] = x['province']
                storeData['city'] = x['city']
                storeData['area'] = x['area']
                storeData['address'] = x['address']
                storeData['longitude'] = x['longitude']
                storeData['latitude'] = x['latitude']
                storeData['machineId'] = x['machineId']
                storeData['machineNum'] = x['machineNum']
                storeData['storeUrl'] = util.server_url + x['storeUrl']
                storeData['workTime'] = x['workTime']
                storeData['distance'] = haversine(float(longitude), float(latitude), float(x['longitude']),
                                                  float(x['latitude']))
                data.append(storeData)
            sorted_x = sorted(data, key=lambda k: k['distance'])
            data = sorted_x
    except Exception as e:
        print e
        data = []
        code = util.CODE_ERROR
    data = {
        'code': code,
        'data': data
    }
    return util.to_json(data)


def haversine(lon1, lat1, lon2, lat2):  # 经度1，纬度1，经度2，纬度2 （十进制度数）
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # 将十进制度数转化为弧度
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine公式
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    c = 2 * asin(sqrt(a))
    r = 6371  # 地球平均半径，单位为公里
    return round(float(c * r), 2)


# 支付列表
@api.route('/api/recharge/list', methods=['POST', 'GET'])
def api_recharge_list():
    try:
        openId = request.values.get('openId', '')
        mysql = Mysql()
        sql = "select * from recharge  where status=1 order by weight asc, id desc"
        sql2 = "select buy_recharge FROM car_users WHERE wxOpenId = '%s'" % openId
        result = mysql.getAll(sql, None)
        user = mysql.getOne(sql2, None)
        mysql.dispose()
        data = []
        code = util.CODE_EMPTY
        if result:
            result = list(result)
            if user:
                buy_list = user['buy_recharge'].split(',')
                for d in result:
                    if str(d['id']) in buy_list and d['property'] == 1:
                        result.remove(d)
                data = result
            else:
                data = result
            if len(result) > 0:
                code = util.CODE_SUCCESS
    except Exception as e:
        print e
        code = util.CODE_ERROR
        data = []
    data = {
        'code': code,
        'data': data
    }
    return util.to_json(data)


# 订单列表
@api.route('/api/order/list', methods=['POST', 'GET'])
def api_order_list():
    try:
        openId = request.values.get('openId')
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        mysql = Mysql()
        sql = "select b.orderNum,b.payTime,b.price,b.payType, r.name recharge FROM car_orders b" \
              " LEFT JOIN car_users a ON a.uid = b.uid LEFT JOIN recharge r ON r.id = b.recharge_id WHERE " \
              "a.wxOpenId = '%s' AND b.status = 1 ORDER BY b.payTime desc limit %d, %d" % (openId, num, util.PAGE_NUM)
        result = mysql.getAll(sql, None)
        mysql.dispose()
        code = util.CODE_EMPTY
        data = []
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                x['payTime'] = x['payTime'].strftime('%Y-%m-%d %H:%M:%S')
                x['price'] = str(x['price'])
                x['recharge'] = x['recharge'] if x['recharge'] else '未知'
            data = result
    except Exception as e:
        print e
        data = []
        code = util.CODE_ERROR
    data = {
        'code': code,
        'data': data,
    }
    return util.to_json(data)


# 洗车记录
@api.route('/api/washed/list', methods=['POST', 'GET'])
def api_wash_list():
    try:
        openId = request.values.get('openId')
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        mysql = Mysql()
        sql = "select b.*,c.storeName from car_users as a right join car_wash as b on a.uid=b.uid left join store as c on c.storeId= b.storeId where a.wxOpenId='%s'" \
              "order by washTime desc limit %d,%d " % (openId, num, util.PAGE_NUM)

        result = mysql.getAll(sql, None)
        mysql.dispose()
        code = util.CODE_EMPTY
        data = []
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                if x['washTime'] is not None:
                    x['washTime'] = x['washTime'].strftime('%Y-%m-%d %H:%M:%S')
            data = result
    except Exception as e:
        print e
        data = []
        code = util.CODE_ERROR
    data = {
        'code': code,
        'data': data,
    }
    return util.to_json(data)


# 获取用户信息
@api.route('/api/user_detail', methods=['post'])
def user_detail():
    data = {}
    data['code'] = util.CODE_EMPTY
    data['car_num'] = 0
    data['count'] = 0
    data['user'] = {}
    data['card_num'] = 0
    try:
        openId = request.values.get('openId')
        sql = "select uid, wxNickName, wxHeadImg, phone FROM car_users WHERE wxOpenId = '%s'" % openId
        mysql = Mysql()
        res = mysql.getOne(sql, None)
        mysql.dispose()
        if res is None:
            return util.to_json(data)
        sql2 = "select if(sum(recharge_num), sum(recharge_num), 0) recharge_num, if(sum(use_num), sum(use_num), 0) " \
               "use_num FROM user_taocan WHERE uid = '%s' AND end_time > now()" % res['uid']
        sql3 = "select count(*) con FROM car_plate WHERE uid = '%s'" % res['uid']
        sql4 = "select count(*) con FROM user_taocan WHERE uid = '%s'" % res['uid']
        mysql = Mysql()
        card_num = mysql.getOne(sql2, None)
        cont = mysql.getOne(sql3, None)
        taocan = mysql.getOne(sql4, None)
        mysql.dispose()
        data['code'] = util.CODE_SUCCESS
        data['user'] = res
        data['count'] = float(card_num['recharge_num']) - float(card_num['use_num'])
        data['car_num'] = cont['con'] if cont else 0
        data['card_num'] = taocan['con'] if taocan else 0
    except Exception as e:
        print e
        data['code'] = util.CODE_ERROR
    return util.to_json(data)


@api.route('/api/user/info', methods=['POST', 'GET'])
def api_user_info():
    try:
        openId = request.values.get('openId')
        mysql = Mysql()
        sql = "select uid, wxNickName,wxHeadImg,washNum,plateNum,phone from car_users where wxOpenId='%s' " % openId
        sql1 = "select count(*) from car_users as a right join car_wash as b on a.uid=b.uid left join store as c on c.storeId= b.storeId where a.wxOpenId='%s'" % openId
        sql2 = "select sum(b.price) as total_money from car_users as a left join" \
               " car_orders as b on a.uid=b.uid where a.wxOpenId='%s' and b.status=1" % (openId)
        result = mysql.getOne(sql, None)
        cont = mysql.getOne(sql1, None)
        total_result = mysql.getOne(sql2, None)
        if cont:
            count = cont['count(*)']
        else:
            count = 0
        mysql.dispose()
        if total_result:
            if total_result['total_money'] is None:
                total_money = 0
            else:
                total_money = total_result['total_money']
        else:
            total_money = 0
        code = util.CODE_SUCCESS
    except Exception as e:
        print e
        code = util.CODE_ERROR
        result = {}
        count = 0
        total_money = 0
    data = {
        'result': result,
        'code': code,
        'count': count,
        'total_money': total_money
    }
    return util.to_json(data)


# 绑定手机号
@api.route('/api/bind/phone', methods=['POST', 'GET'])
def api_bind_phone():
    openId = request.values.get('openId')
    phone = request.values.get('phone')
    mysql = Mysql()
    sql = "update car_users set phone='%s' where wxOpenId='%s'" % (phone, openId)
    res = mysql.update(sql, None)
    mysql.dispose()
    code = util.CODE_FAIL
    if res:
        code = util.CODE_SUCCESS
    data = {
        'code': code
    }
    return util.to_json(data)


@api.route('/api/wash/model', methods=['POST', 'GET'])
def api_wash_model():
    try:
        mysql = Mysql()
        sql = "select modelName,modelPrice from wash_model where status=1"
        result = mysql.getAll(sql, None)
        mysql.dispose()
        code = util.CODE_EMPTY
        data = []
        if result:
            code = util.CODE_SUCCESS
            data = result
    except Exception as e:
        print e
        code = util.CODE_ERROR
        data = []
    data = {
        'data': data,
        'code': code
    }
    return util.to_json(data)
